package ar.edu.utn.frsf.cidisi.ginet.generation.pnml2wscdl.elementstemplate;

import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.pnml.tools.epnk.pnmlcoremodel.Page;
import org.pnml.tools.epnk.pnmlcoremodel.PlaceNode;
import org.w3._2005._10.cdl.CdlFactory;
import org.w3._2005._10.cdl.TAssign;
import org.w3._2005._10.cdl.TChoreography;
import org.w3._2005._10.cdl.TCopy;
import org.w3._2005._10.cdl.TSequence;
import org.w3._2005._10.cdl.TVariableRef;

public class InteractionProtocolWSCDL extends WSCDLStructure{
	
	public InteractionProtocolWSCDL(Page page, TChoreography choreography){
		this.page = page;
		this.choreography = choreography;
	}
	
	public TSequence createWSCDLElement(){
		
		EList<Page> pages = this.getPages(page);
		
		TSequence sequence = CdlFactory.eINSTANCE.createTSequence();
		
		boolean hasTermination = this.hasTermination(page);
		
		for (Page pageElement : pages) {
			this.addTo(sequence, this.createPackageWscdl(pageElement, this.choreography));
		}
		
		if(hasTermination){
			
			TAssign assign = CdlFactory.eINSTANCE.createTAssign();
			
			EList<TCopy> copies = new BasicEList<TCopy>();
			
			TCopy copy = CdlFactory.eINSTANCE.createTCopy();
			
			copies.add(copy);
			
			TVariableRef var = CdlFactory.eINSTANCE.createTVariableRef();
			
			var.setVariable("cdl:getVariable('Termination')");

			copy.setTarget(var);
			
			assign.getCopy().add(copy);
			
			sequence.getAssign().add(assign);			
		}
		
		return sequence;
	}

	private boolean hasTermination(Page page) {

		for (Object element : page.getObject()) {
			if(element instanceof PlaceNode){
				if(((PlaceNode)element).getName().getText().toUpperCase().equals("TERMINATION")){
					return true;
				}
			}
		}
		return false;
	}

}
